<template>
  <el-card class="list-page">
    <div class="list-h">
      <div class="form-left">
        <el-button
          type="primary"
          @click="handleDetail(1, {})"
          v-auth="`/projectsA/budget--add`"
          class="add-option"
          >增加预算</el-button
        >
        <el-button
          type="primary"
          @click="exportFunc"
          v-auth="`/projectsA/budget--export`"
          class="add-option"
          >导出</el-button
        >
        <p>
          项目总预算（万元）：<span>{{ budgetTotal }}</span>
        </p>
      </div>

      <el-form
        :inline="true"
        :model="formInline"
        ref="formRef"
        class="demo-form-inline"
      >
        <el-form-item label="预算名称" prop="budgetNameLike">
          <el-input
            clearable
            class="width-custom140"
            v-model="formInline.budgetNameLike"
            placeholder="请输入预算名称"
          />
        </el-form-item>

        <el-form-item label="预算类型" prop="budgetTypeCode">
          <el-select
            class="width-custom140"
            v-model="formInline.budgetTypeCode"
            clearable
            filterable
          >
            <el-option
              v-for="item in budgetTypeList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="关联集采项目" prop="jcProjectId">
          <el-select
            clearable
            filterable
            class="width-custom140"
            v-model="formInline.jcProjectId"
          >
            <el-option
              v-for="item in jcProjectTable"
              :label="item.jcProjectName"
              :key="item.jcProjectId"
              :value="item.jcProjectId"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            @click="handleSearch"
            v-auth="`/projectsA/budget--query`"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-skeleton
      style="height: calc(100vh - 400px)"
      :rows="8"
      :loading="loading"
      animated
    >
    </el-skeleton>
    <el-table
      :data="tableData"
      stripe
      v-loading="loading"
      v-show="!loading"
      :height="'calc(100vh - 400px)'"
      :header-cell-style="{
        background: '#F7F9FD',
        color: '#000',
        height: '48px',
        borderTop: '1px soild #E4E8F2'
      }"
    >
      <template #empty>
        <el-empty :image-size="150" description="暂无数据"></el-empty>
      </template>
      <el-table-column type="index" label="序号" width="80">
        <template v-slot="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="budgetName" label="预算名称"> </el-table-column>
      <el-table-column prop="budgetAmount" label="预算金额（万）">
      </el-table-column>
      <el-table-column prop="contractAmount" label="合同金额(万)">
        <template #default="{ row }">
          <span
            :class="
              Number(row.contractAmount) > Number(row.budgetAmount)
                ? 'text-danger'
                : ''
            "
            >{{ row.contractAmount }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="rate" label="费率(%)"> </el-table-column>
      <el-table-column prop="budgetTypeName" label="预算类型">
      </el-table-column>
      <el-table-column prop="jcProjectName" label="关联集采项目">
        <template #default="{ row }">
          <span class="text-link" size="small" @click="jumpLink(1)">{{
            row.jcProjectName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sectionName" label="对应标段">
        <template #default="{ row }">
          <span class="text-link" size="small" @click="jumpLink(2)">{{
            row.sectionName
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createUserName" label="创建人"> </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="{ row }">
          <template v-if="row.ext1 == 2">
            <el-button
              type="text"
              size="small"
              @click="handleDetail(2, row)"
              v-auth="`/projectsA/budget--edit`"
              >编辑</el-button
            >
            <el-button
              type="text"
              size="small"
              class="btns-danger"
              @click="showDeleteMessageBox(row)"
              v-auth="`/projectsA/budget--delete`"
              >删除</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>
    <re-pagination
      v-if="total > 0"
      :total="total"
      v-model:page="formInline.pageNum"
      v-model:limit="formInline.pageSize"
      @pagination="handleChangePage"
    />
    <budget-detail
      v-if="detailData.dialogFormVisible"
      :detailData="detailData"
      :budgetTypeList="budgetTypeList"
      @emitClose="detailData.dialogFormVisible = false"
      @updateClose="updateClose"
    />
  </el-card>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import RePagination from "/@/components/RePagination/index.vue";
import { storageLocal } from "/@/utils/storage";
import {
  budgetList,
  jcProjectList,
  delProjectBudget,
  budgetStatistics
} from "/@/api/purchase";
import { postDictList } from "/@/api/home";
import budgetDetail from "./components/budgetDetail.vue";
import { ElMessageBox } from "element-plus";
import NotifMessage from "/@/utils/message/notification";
import { exportExcel } from "/@/utils/file";
export default defineComponent({
  name: "budget",
  components: { RePagination, budgetDetail },
  setup() {
    const router = useRouter();
    const formRef = ref<HTMLFormElement | null>(null) as any;
    let projectInfo = storageLocal.getItem("projectInfo");
    let formInline = reactive({
      budgetNameLike: "",
      budgetTypeCode: "",
      jcProjectId: "",
      projectId: +projectInfo?.id,
      pageNum: 1,
      pageSize: 10
    });
    const jcProjectTable = ref([]);
    const budgetTypeList = ref([]);
    const tableData = ref([]);
    const total = ref<number>(0);
    const budgetTotal = ref<number>(0);
    const loading = ref<boolean>(false);
    const detailData = reactive({
      title: "新增预算",
      type: 1,
      id: "",
      dialogFormVisible: false
    });
    //获取数据列表
    const getTableList = async (obj: object = {}) => {
      try {
        loading.value = true;
        const { code, data } = await budgetList({
          ...obj
        });
        if (code === 200) {
          tableData.value = data.list;
          total.value = data.rows;
          getBudgetStatistics();
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    };

    //统计总预算
    const getBudgetStatistics = async () => {
      try {
        loading.value = true;
        const { code, data } = await budgetStatistics({
          projectId: +projectInfo?.id
        });
        if (code === 200) {
          budgetTotal.value = data.budgetStatistics;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    };

    //新增编辑预算
    const handleDetail = async (type, row) => {
      if (type === 1) {
        detailData.title = "新增预算";
        detailData.type = 1;
        detailData.id = "";
      } else {
        detailData.title = "编辑预算";
        detailData.type = 2;
        detailData.id = row.id;
      }
      detailData.dialogFormVisible = true;
    };

    const showDeleteMessageBox = row => {
      ElMessageBox.confirm("确定删除该条记录吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        iconClass: "el-icon-warning"
      })
        .then(() => {
          handleDelete(row);
        })
        .catch(() => {});
    };

    //删除预算
    const handleDelete = async row => {
      try {
        const { code, message } = await delProjectBudget({ id: row.id });
        if (code === 200) {
          NotifMessage.success(message);
          getTableList(formInline);
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleChangePage = () => {
      getTableList(formInline);
    };

    const handleSearch = () => {
      formInline.pageNum = 1;
      getTableList(formInline);
    };

    const handleReset = (): void => {
      formRef.value.resetFields();
      getTableList(formInline);
    };

    const updateClose = async () => {
      getTableList(formInline);
      detailData.dialogFormVisible = false;
    };

    const jumpLink = async type => {
      if (type === 1) {
        router.push(`/projects/purchase/project`);
      } else {
        router.push(`/projectsA/proManage/section`);
      }
    };

    // 数据字典,获取预算类型
    const initPostDictList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_cen_budget_type" });
        budgetTypeList.value = data;
      } catch (err) {
        console.log(err);
      }
    };

    //获取下拉框关联集采项目
    const getJcProjectList = async () => {
      const searchInline = {
        projectId: +projectInfo?.id,
        ext1: "1"
      };
      try {
        const { data } = await jcProjectList(searchInline);
        jcProjectTable.value = data;
      } catch (err) {
        console.log(err);
      }
    };

    const exportFunc = async () => {
      let formData = {
        ...formInline,
        pageNum: 1,
        pageSize: 0
      };
      exportExcel(
        "/snow-admin/projectBudget/export",
        formData,
        `${projectInfo?.name}_项目预算`
      );
    };

    getJcProjectList();
    initPostDictList();
    getTableList(formInline);
    return {
      handleSearch,
      formInline,
      loading,
      tableData,
      total,
      budgetTotal,
      detailData,
      handleDetail,
      updateClose,
      showDeleteMessageBox,
      budgetTypeList,
      jcProjectTable,
      handleChangePage,
      handleReset,
      formRef,
      jumpLink,
      exportFunc
    };
  }
});
</script>
<style>
.el-icon-warning {
  color: #e45d5d !important;
}
</style>
<style lang="scss" scoped>
.form-left {
  display: flex;
  align-items: center;
  p {
    margin-bottom: 12px;
    font-size: 14px;
    margin-left: 10px;
    font-weight: 400;
    color: #494c53;
    span {
      font-size: 20px;
      font-weight: 600;
      color: #494c53;
    }
  }
  .text-danger {
    color: #e45d5d;
  }
}
.text-link {
  color: #5298ff;
  cursor: pointer;
}
</style>
